package com.yf.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yf.mapper.system.SysUserRoleMapper;
import com.yf.model.system.entity.SysUserRole;
import com.yf.service.ISysUserRoleService;
import com.yf.utils.BindingUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.Set;
import java.util.stream.Collectors;

/**
 * 用户和角色关联表-SysUserRoleIServiceImpl
 *
 * @author YiFei
 * @since 2024-04-23 18:43:36
 */
@Service("sysUserRoleService")
public class SysUserRoleIServiceImpl extends ServiceImpl<SysUserRoleMapper, SysUserRole> implements ISysUserRoleService {

    /**
     * 保存用户角色信息
     *
     * @param userId  用户id
     * @param roleIds 用户角色信息
     * @return 是否保存成功
     */
    @Transactional(propagation = Propagation.REQUIRED)
    @Override
    public boolean saveUserRole(Long userId, Set<Integer> roleIds) {
        if (userId == null || CollectionUtils.isEmpty(roleIds)) {
            return false;
        }

        return BindingUtil.bindEntities(
                userId,
                roleIds,
                // 查询用户角色信息
                (id) -> this.lambdaQuery()
                        .eq(SysUserRole::getUserId, id)
                        .list()
                        .stream()
                        .map(SysUserRole::getRoleId)
                        .collect(Collectors.toSet()),
                (id, bindIds) -> {
                    // 绑定用户角色信息
                    this.saveBatch(bindIds.stream()
                            .map(roleId -> SysUserRole.builder()
                                    .userId(id)
                                    .roleId(roleId)
                                    .build())
                            .collect(Collectors.toList()));
                },
                (id, unBindIds) -> {
                    // 删除用户角色信息
                    this.lambdaUpdate()
                            .eq(SysUserRole::getUserId, id)
                            .in(SysUserRole::getRoleId, unBindIds)
                            .remove();
                }
        );
    }
}

